package rpc.log;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import rpc.core.FlowReq;
import rpc.core.FlowRes;

public class SimpleLogFormatter implements LogFormatter {

  @Override
  public String toLogStr(FlowReq req) {
    return map2Str(req.toMap());
  }

  @Override
  public String toLogStr(FlowRes res) {
    return map2Str(res.toMap());
  }

  private String map2Str(Map<String, Object> map) {
    if (Objects.isNull(map) || map.size() == 0) {
      return "";
    }
    StringBuilder sb = new StringBuilder("");
    map.entrySet().forEach(e -> {
      Object value = e.getValue();
      if (!(value instanceof List)) {
        sb.append(e.getKey()).append(":").append(value).append(",");
      } else {
        List list = (List) value;
        Object o = list.get(0);
        sb.append(e.getKey()).append("Size:").append(list.size()).append(",f:{").append(o).append("}");
      }
    });
    return sb.substring(0, sb.length() - 1);
  }
}
